package com.easylive.service.impl;

import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import cn.hutool.core.bean.BeanUtil;
import com.easylive.component.RedisComponent;
import com.easylive.entity.constants.Constants;
import com.easylive.entity.dto.TokenUserInfoDto;
import com.easylive.entity.enums.ResponseCodeEnum;
import com.easylive.entity.enums.UserSexEnum;
import com.easylive.entity.enums.UserStatusEnum;
import com.easylive.entity.po.UserFocus;
import com.easylive.entity.query.UserFocusQuery;
import com.easylive.exception.BusinessException;
import com.easylive.mappers.UserFocusMapper;
import com.easylive.utils.MD5Util;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import com.easylive.entity.enums.PageSize;
import com.easylive.entity.query.UserInfoQuery;
import com.easylive.entity.po.UserInfo;
import com.easylive.entity.vo.PaginationResultVO;
import com.easylive.entity.query.SimplePage;
import com.easylive.mappers.UserInfoMapper;
import com.easylive.service.UserInfoService;
import com.easylive.utils.StringTools;
import org.springframework.transaction.annotation.Transactional;


/**
 * 用户信息表 业务接口实现
 */
@Service("userInfoService")
public class UserInfoServiceImpl implements UserInfoService {

	@Resource
	private UserInfoMapper<UserInfo, UserInfoQuery> userInfoMapper;

	@Resource
	private UserFocusMapper<UserFocus, UserFocusQuery> userFocusMapper;

	@Resource
	private RedisComponent redisComponent;

	/**
	 * 根据条件查询列表
	 */
	@Override
	public List<UserInfo> findListByParam(UserInfoQuery param) {
		return this.userInfoMapper.selectList(param);
	}

	/**
	 * 根据条件查询列表
	 */
	@Override
	public Integer findCountByParam(UserInfoQuery param) {
		return this.userInfoMapper.selectCount(param);
	}

	/**
	 * 分页查询方法
	 */
	@Override
	public PaginationResultVO<UserInfo> findListByPage(UserInfoQuery param) {
		int count = this.findCountByParam(param);
		int pageSize = param.getPageSize() == null ? PageSize.SIZE15.getSize() : param.getPageSize();

		SimplePage page = new SimplePage(param.getPageNo(), count, pageSize);
		param.setSimplePage(page);
		List<UserInfo> list = this.findListByParam(param);
		PaginationResultVO<UserInfo> result = new PaginationResultVO(count, page.getPageSize(), page.getPageNo(), page.getPageTotal(), list);
		return result;
	}

	/**
	 * 新增
	 */
	@Override
	public Integer add(UserInfo bean) {
		return this.userInfoMapper.insert(bean);
	}

	/**
	 * 批量新增
	 */
	@Override
	public Integer addBatch(List<UserInfo> listBean) {
		if (listBean == null || listBean.isEmpty()) {
			return 0;
		}
		return this.userInfoMapper.insertBatch(listBean);
	}

	/**
	 * 批量新增或者修改
	 */
	@Override
	public Integer addOrUpdateBatch(List<UserInfo> listBean) {
		if (listBean == null || listBean.isEmpty()) {
			return 0;
		}
		return this.userInfoMapper.insertOrUpdateBatch(listBean);
	}

	/**
	 * 多条件更新
	 */
	@Override
	public Integer updateByParam(UserInfo bean, UserInfoQuery param) {
		StringTools.checkParam(param);
		return this.userInfoMapper.updateByParam(bean, param);
	}

	/**
	 * 多条件删除
	 */
	@Override
	public Integer deleteByParam(UserInfoQuery param) {
		StringTools.checkParam(param);
		return this.userInfoMapper.deleteByParam(param);
	}

	/**
	 * 根据UserId获取对象
	 */
	@Override
	public UserInfo getUserInfoByUserId(String userId) {
		return this.userInfoMapper.selectByUserId(userId);
	}

	/**
	 * 根据UserId修改
	 */
	@Override
	public Integer updateUserInfoByUserId(UserInfo bean, String userId) {
		return this.userInfoMapper.updateByUserId(bean, userId);
	}

	/**
	 * 根据UserId删除
	 */
	@Override
	public Integer deleteUserInfoByUserId(String userId) {
		return this.userInfoMapper.deleteByUserId(userId);
	}

	/**
	 * 根据Email获取对象
	 */
	@Override
	public UserInfo getUserInfoByEmail(String email) {
		return this.userInfoMapper.selectByEmail(email);
	}

	/**
	 * 根据Email修改
	 */
	@Override
	public Integer updateUserInfoByEmail(UserInfo bean, String email) {
		return this.userInfoMapper.updateByEmail(bean, email);
	}

	/**
	 * 根据Email删除
	 */
	@Override
	public Integer deleteUserInfoByEmail(String email) {
		return this.userInfoMapper.deleteByEmail(email);
	}

	/**
	 * 根据NickName获取对象
	 */
	@Override
	public UserInfo getUserInfoByNickName(String nickName) {
		return this.userInfoMapper.selectByNickName(nickName);
	}

	/**
	 * 根据NickName修改
	 */
	@Override
	public Integer updateUserInfoByNickName(UserInfo bean, String nickName) {
		return this.userInfoMapper.updateByNickName(bean, nickName);
	}
	/**
	 * 根据NickName删除
	 */
	@Override
	public Integer deleteUserInfoByNickName(String nickName) {
		return this.userInfoMapper.deleteByNickName(nickName);
	}

	@Override
	public void register(String email, String nickName, String registerPassword) {
//		UserInfo userInfo = this.userInfoMapper.selectByEmail(email);
//		if(userInfo != null){
//			UserInfo userInfo2 = this.userInfoMapper.selectByNickName(nickName);
//			if(userInfo2 != null){
//				UserInfo userInfoNew = new UserInfo();
//				userInfoNew.setNickName(nickName);
//				userInfoNew.setUserId(StringTools.getRandomNumber(Constants.Length_10));
//				userInfoNew.setEmail(email);
//				userInfoNew.setPassword(StringTools.encodeByMD5(registerPassword));
//				userInfoNew.setJoinTime(new Date());
//				userInfoNew.setStatus(UserStatusEnum.ENABLE.getStatus());
//				userInfoNew.setSex(UserSexEnum.UNKNOWN.getSex());
//				userInfoNew.setTheme(Constants.ONE);
//				//TODO 初始化用户硬币
//				this.userInfoMapper.insert(userInfoNew);
//				return true;
//			}else {
//				return false;
//			}
//		}else{
//			return false;
//		}
		UserInfo userInfo = this.userInfoMapper.selectByEmail(email);
		if(userInfo != null){
			throw new BusinessException("邮箱已被注册");
		}
		UserInfo userInfo2 = this.userInfoMapper.selectByNickName(nickName);
		if(userInfo2 != null){
			throw new BusinessException("昵称已被注册");
		}

		UserInfo userInfoNew = new UserInfo();
				userInfoNew.setNickName(nickName);
				userInfoNew.setUserId(StringTools.getRandomNumber(Constants.Length_10));
				userInfoNew.setEmail(email);
				userInfoNew.setPassword(MD5Util.MD5Lower(registerPassword));
				userInfoNew.setJoinTime(new Date());
				userInfoNew.setStatus(UserStatusEnum.ENABLE.getStatus());
				userInfoNew.setSex(UserSexEnum.UNKNOWN.getSex());
				userInfoNew.setTheme(Constants.ONE);

				this.userInfoMapper.insert(userInfoNew);

	}

	@Override
	public TokenUserInfoDto login(String email, String password, String ip) {
		UserInfo userInfo = this.userInfoMapper.selectByEmail(email);
		System.out.println(userInfo);
		if(userInfo == null || !userInfo.getPassword().equals(password)){
			throw new BusinessException("账号或密码错误");
		}
		if(userInfo.getStatus().equals(UserStatusEnum.DISABLE.getStatus())){
			throw new BusinessException("账号已被禁用");
		}
		UserInfo updateUserInfo = new UserInfo();
		updateUserInfo.setLastLoginIp(ip);
		updateUserInfo.setLastLoginTime(new Date());
		this.userInfoMapper.updateByUserId(updateUserInfo, userInfo.getUserId());

		TokenUserInfoDto tokenUserInfoDto = BeanUtil.copyProperties(userInfo, TokenUserInfoDto.class);
		redisComponent.saveTokenInfo(tokenUserInfoDto);

		return tokenUserInfoDto;
	}

	@Override
	public UserInfo getUserDetailInfo(String currentUserId, String userId) {
		UserInfo userInfo = this.userInfoMapper.selectByUserId(userId);
		if(userInfo == null){
			throw new BusinessException(ResponseCodeEnum.CODE_404);
		}
		//TODO 获赞，播放
		Integer fansCount = userFocusMapper.selectFansCount(userId);
		Integer focusCount = userFocusMapper.selectFocusCount(userId);

		userInfo.setFansCount(fansCount);
		userInfo.setFocusCount(focusCount);

		if(currentUserId == null){
			userInfo.setHaveFocus(false);
		}else{
			UserFocus userFocus = userFocusMapper.selectByUserIdAndFocusUserId(currentUserId, userId);
			userInfo.setHaveFocus(userFocus == null ? false : true);
		}


		return userInfo;
	}

	@Override
	@Transactional
	public void updateUserInfo(UserInfo userInfo, TokenUserInfoDto tokenUserInfoDto) {
		UserInfo dbUserInfo = this.userInfoMapper.selectByUserId(userInfo.getUserId());
		if(!dbUserInfo.getNickName().equals(userInfo.getNickName()) && dbUserInfo.getCurrentCoinCount() < Constants.UPDATE_NICKNAME_COIN_COST){
			throw new BusinessException("硬币不足!!");
		}
		if(!dbUserInfo.getNickName().equals(userInfo.getNickName())){
			Integer count = this.userInfoMapper.updateCoinCount(userInfo.getUserId(), -Constants.UPDATE_NICKNAME_COIN_COST);
			if(count == 0){
				throw new BusinessException("硬币不足!!");
			}
		}
		userInfoMapper.updateByUserId(userInfo, userInfo.getUserId());
		Boolean updateTokenInfo = false;
		if(!userInfo.getAvater().equals(tokenUserInfoDto.getAvatar())){
			tokenUserInfoDto.setAvatar(userInfo.getAvater());
			updateTokenInfo = true;
		}
		if(!userInfo.getNickName().equals(tokenUserInfoDto.getNickName())){
			tokenUserInfoDto.setNickName(userInfo.getNickName());
			updateTokenInfo = true;
		}
		if(updateTokenInfo){
			redisComponent.updateTokenInfo(tokenUserInfoDto);
		}
	}
}